package theTVDB.com.command
{

	import com.adobe.cairngorm.control.CairngormEvent;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.AsyncToken;
	import mx.rpc.http.HTTPService;
	
	import theTVDB.com.event.SearchSeriesEvent;
	import theTVDB.com.service.Services;
	import theTVDB.com.vo.SeriesSearchVO;


	public class SearchSeriesCommand extends CallbackCommand
	{
		private var services:Services = Services.getInstance() as Services;
		private var _searchString:String;

		override public function result(data:Object):void
		{
			var SearchResults:XML = (data.result as XML);
			var seriesData:XML;

			var result:ArrayCollection = new ArrayCollection()

			for each (seriesData in SearchResults..Series)
			{
				var seriesVO:SeriesSearchVO  = new SeriesSearchVO();
				seriesVO.banner = seriesData.banner;
				seriesVO.firstAired = seriesData.FirstAired;
				seriesVO.id = seriesData.id;
				seriesVO.IMDB_id = seriesData.IMDB_ID;
				seriesVO.language = seriesData.language;
				seriesVO.overview = seriesData.Overview;
				seriesVO.seriesid = seriesData.seriesid;
				seriesVO.seriesName = seriesData.SeriesName;
				seriesVO.zap2it_id = seriesData.zap2it_id;
				result.addItem(seriesVO);
			}

			if (callback != null)
				callback(result, _searchString);

		}

		override public function fault(info:Object):void
		{
			trace(info);
			
			if (callback != null)
				callback(null, _searchString);
		}

		override public function execute( event : CairngormEvent ) : void
		{
			
			callback = (event as SearchSeriesEvent).callback;
			_searchString = (event as SearchSeriesEvent).seriesName;
			var service:HTTPService = services.searchSeries;
			var params:Object = {};
			params["seriesname"] = (event as SearchSeriesEvent).seriesName;
			if ((event as SearchSeriesEvent).language != null)
				params["language"] = (event as SearchSeriesEvent).language;

			var token:AsyncToken = service.send(params);
			token.addResponder(this);
		}
	}
}
